<script setup>
import { login, sign } from '@/api/user.js'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import { watch } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import { ref } from 'vue'

defineOptions({
  name: 'loginForm'
})
const props = defineProps(['isLogin'])

const emit = defineEmits(['togIsLogin'])

const router = useRouter()
const userStore = useUserStore()

const fd = ref({
  name: '',
  password: '',
  password_confirmation: '',
  email: ''
})
const onSubmit = async (values) => {
  if (props.isLogin) {
    const res = await login(values)
    if (res.access_token) {
      showNotify({
        type: 'success',
        message: '登录成功'
      })
      userStore.setToken(res.access_token)
      router.push('/home')
    }
  } else {
    const res = await sign(values)
    if (res.status >= 200 && res.status < 300) {
      showNotify({
        type: 'success',
        message: '注册成功'
      })
    }
  }
}
watch(
  () => props.isLogin,
  () => Object.keys(fd.value).forEach((item) => (fd.value[item] = ''))
)
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        autocomplete="off"
        v-model="fd.name"
        :name="props.isLogin ? 'email' : 'name'"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="fd.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,18}$/,
            message: '长度为8-16的大小写字母数字和下划线_'
          }
        ]"
      />
      <template v-if="!props.isLogin">
        <van-field
          v-model="fd.password_confirmation"
          type="password"
          name="password_confirmation"
          label="确认密码"
          placeholder="确认密码"
          :rules="[
            { required: true, message: '请填写密码' },
            {
              validator(value) {
                if (value !== fd.password) return '密码不一致'
                return true
              }
            }
          ]"
        />
        <van-field
          v-model="fd.email"
          autocomplete="off"
          type="email"
          name="email"
          label="电子邮箱"
          placeholder="电子邮箱"
          :rules="[{ required: true, message: '邮箱填写' }]"
        />
      </template>
    </van-cell-group>
    <div style="margin: 16px">
      <h6 style="color: orangered" @click="emit('togIsLogin', !props.isLogin)">
        {{ props.isLogin ? '没有账号，立即注册' : '已有帐号，立即登录' }}
      </h6>
      <van-button round block type="warning" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped lang="scss"></style>
